var MemberProxy = require('../../proxy/member.js');
var WorkspaceProxy = require('../../proxy/workspace.js');
//var mongoose  = require('mongoose');
var Workspace = require('../../models/workspace.js');
var request = require('request');
var config = require('../../config.json');
var waterfall = require('async-waterfall');
var delWorkspace = require('./workspace/workspace.js').delWorkspace;
var EventProxy = require('eventproxy');
var _ = require('lodash');

exports.addMember = function (req, resp, next) {
    var member_info = req.body;

    MemberProxy.getMembers(member_info.projectId, function (err, data) {
        if (err) {
            logger.error("添加成员失败");
            logger.error(err);
            return resp.format_json(null, 500, "添加成员失败!" );
        }
        if (_.findIndex(data, {user: member_info.user}) >= 0) {
            return resp.format_json({}, 204, "成员已存在");
        }
        MemberProxy.addMember(member_info, function (err, data) {
            if (err) {
                logger.error("添加成员失败");
                logger.error(err);
                return resp.format_json(null, 500, "添加成员失败");
            }
            resp.format_json(data, 0);
        });

    });


    //    }
    //});
};

/**
 * 删除成员时 检查是否有工作空间 有的话 删除
 * @param req
 * @param res
 * @param next
 */
exports.removeMember = function (req, res, next) {
    var body = req.body;
    var memberSelected = body.member_id;
    var project_id = body.project_id;
    var ep = new EventProxy();
    ep.fail(function () {
        return res.format_json(null, 501, "删除成员工作空间失败");
    });

    MemberProxy.removeMember(memberSelected, function (err, data) {
        if (err) {
            return res.format_json(null, 500, "删除成员失败");
        } else {
            var user_shortId = data.user;
            var condition = {
                "project_id": project_id,
                "user": {
                    "$elemMatch": {"shortId": user_shortId, role: "creator"}
                }
            };

            ep.on("workspace_deleted", function () {
                var me_condition = {
                    "project_id": project_id,
                    "user": {
                        "$elemMatch": {"shortId": user_shortId, role: {$in: ["developer", "admin", "observer"]}}
                    }
                };
                Workspace.find(me_condition, function (err, workspaces) {
                    if (workspaces && workspaces.length > 0) {
                        ep.after("remove_member", workspaces.length, function () {
                            return res.format_json("成员删除成功", 200, null);
                        });
                        workspaces.map(function (workspace) {
                            _.remove(workspace.user, function (it) {
                                return it.shortId == user_shortId;
                            });
                            WorkspaceProxy.updateMembers(workspace, workspace.user, function (err, data) {
                                if (err) {
                                    logger.error(err);
                                    res.status(500);
                                    return res.format_json(null, 500, "从" + workspace.title + "中移除成员失败");
                                }
                                ep.emit("remove_member");
                            });
                        });
                    }else{
                        res.format_json("成员删除成功", 200, null);
                    }
                });
            });
            Workspace.find(condition).populate('project_id').exec(function (err, workspaces) {
                if (workspaces && workspaces.length > 0) {
                    ep.after("delete_member_workspace", workspaces.length, function () {
                        ep.emit("workspace_deleted");
                        //res.format_json("成员删除成功", 200, null);
                    });
                    workspaces.map(function (workspace) {
                        var workspace_info = {
                            work_id: workspace._id,
                            namespace: workspace.project_id.namespace,
                            project_name: workspace.project_id.name
                        };
                        delWorkspace(workspace_info, function (err, data) {
                            if (err) {
                                return res.format_json(null, 501, "删除成员工作空间失败");
                            } else {
                                ep.emit("delete_member_workspace");
                            }
                        });
                    });
                } else {
                    res.format_json("成员删除成功", 200, null);
                }
            });
        }
    });
};

exports.updateMember = function (req, res, next) {
    var body = req.body;
    var member_id = body._id;
    var role = body.role;
    MemberProxy.updateMember(member_id, role, function (err, data) {
        if (err) {
            return res.format_json(null, 500, "更新成员信息失败:" + err);
        }
        res.format_json(data, 0);
    });
};

exports.getMembers = function (req, res, next) {
    var projectId = req.params.project_id;
    MemberProxy.getMembers(projectId, function (err, data) {
        if (err) {
            return res.format_json(null, 500, "获取成员信息失败:" + err);
        }
        res.format_json(data, 0);
    });
};

exports.getMembersByshoutids = function (req, res, next) {
    var shortid_arr = JSON.stringify(req.body.shortid);
    var postData = {
        "client_id": config.auth.client_id,
        "client_secret": config.auth.client_secret,
        "shortid": shortid_arr
    }
    request.post({
        url: config.auth.uc_private + "/users/shortid",
        form: postData
    }, function (error, resp) {
        if (!error) {
            res.format_json(JSON.parse(resp.body), 0);
        }
    })
};

function remove_workspace(work_name) {
    var filename = path.join(config.workspace.workspeces_path, config.workspace.space);
    waterfall([
        //2.删除目录，读取space.xml
        function (workspace, cb) {
            var full_name = "workspace" + workspace.work_name;
            removeDir.remove(path.join(root, full_name), function (err) {
                if (err) {
                    logger.error(err);
                    return call_back(err);
                }
                logger.info("删除目录成功");
                //读取space.xml
                fs.readFile(filename, 'utf-8', function (err, data) {
                    if (err) {
                        logger.error(err);
                        return call_back(err);
                    }
                    logger.info("读取space.xml成功");
                    cb(null, workspace, data);
                });
            });
        },
        //3.修改space.xml
        function (workspace, data, cb) {
            X2JPaser.parseString(data, function (err, result) {
                var array = result.workspaces.workspace;
                if (typeof(result.workspaces.workspace) == 'undefined') {
                    logger.error("space.xml不存在");
                    return call_back(err);
                } else {
                    for (var i = 0; i < array.length; i++) {
                        var work = array[i];
                        if (work.$.id == workspace.work_name) {
                            array.splice(i, 1);
                        }
                    }
                    if (array.length == 0) {
                        result.workspaces = {
                            '$': {
                                name: "workspaces"
                            }
                        };
                    } else {
                        result.workspaces.workspace = array;
                    }
                    var xmlString = builder.buildObject(result);
                    logger.info("修改space.xml成功");
                    cb(null, workspace, xmlString);
                }
            });
        },
        //4.写入space.xml 删除数据库数据
        function (workspace, xmlString, cb) {
            fs.writeFile(filename, xmlString, 'utf-8', function (err) {
                if (err) {
                    logger.error(err);
                    return call_back(err);
                }
                logger.info("写入space.xml成功");
                WorkspaceProxy.deleteWorkspace(workspace_id, function (err) {
                    if (err) {
                        logger.error(err);
                        return call_back(err);
                    }
                    logger.info("删除数据库数据成功");
                    cb(null)
                });
            });
        }
    ], function (err) {
        if (err) {
            logger.error(err);
            return call_back(err);
        }
        return call_back(null, "success");
    });
}